package commons.ui.widget;

import java.math.BigDecimal;
import java.text.DecimalFormat;

import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.widgets.Text;

import commons.ui.listener.DoubleVerifyListener;
import commons.utils.ConversionUtils;
import commons.utils.FormatUtils;

/**
 * Custom text field for displaying formatted values. Beeps and ignores
 * characters that cause the content of the control to become unparsable.
 * 
 * @author ted stockwell
 */
public class SimpleCurrencyDecorator {
    private final DecimalFormat _decimalFormat;
    private final Text _text;

    public SimpleCurrencyDecorator(Text text) {
	_text = text;
	_decimalFormat = FormatUtils.DECIMAL_FORMAT;
	init();
    }

    public SimpleCurrencyDecorator(Text text, DecimalFormat decimalFormat) {
	_text = text;
	_decimalFormat = decimalFormat;
	init();
    }

    protected void init() {
	_text.addVerifyListener(new DoubleVerifyListener());

	_text.addFocusListener(new FocusAdapter() {
	    @Override
	    public void focusLost(FocusEvent e) {
		String textValue = _text.getText();
		BigDecimal value = ConversionUtils.toBigDecimal(textValue);
		if (value == null) {
		    return;
		}
		String valueString = value.toString();
		if (textValue.indexOf(",") > -1) {
		    valueString = _decimalFormat.format(value);
		}
		if (!valueString.equals(textValue)) {
		    _text.setText(valueString);
		}
	    }
	});
    }
}
